package com.tssup.fesco.common.config.common;
 
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import com.github.pagehelper.PageHelper;
import com.tssup.fesco.common.frame.mybatis.mapper.SqlMapper;
import com.tssup.fesco.common.frame.mybatis.plugin.PerformanceInterceptor;

@Configuration
//启用注解事务管理，使用CGLib代理
@EnableTransactionManagement()
@Import({DruidConfiguration.class})
public class MyBatisConfig implements TransactionManagementConfigurer {
    
    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    DataSource dataSource;
    
    @Autowired
    SqlSessionFactory sqlSessionFactory;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        
        LOG.info("************************* INIT SESSIONFACTORY ******************");
        LOG.info(dataSource.toString());
        
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        
        // 分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        
        properties.setProperty("dialect", "mysql");
        // 分页参数合理化，默认false禁用 启用合理化时，如果pageNum<1会查询第一页，如果pageNum>pages会查询最后一页
        // 禁用合理化时，如果pageNum<1或pageNum>pages会返回空数据
        properties.setProperty("reasonable", "true");
        
        // 支持通过Mapper接口参数来传递分页参数
        properties.setProperty("supportMethodsArguments", "true");
        
        // always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page
        properties.setProperty("returnPageInfo", "check");
        
        // 为了支持startPage(Object params)方法 增加了一个`params`参数来配置参数映射，用于从Map或ServletRequest中取值
        // 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 pageNum=pageHelperStart;pageSize=pageHelperRows;
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        
        // 添加其他插件
        bean.setPlugins(new Interceptor[]{pageHelper, new PerformanceInterceptor()});
        
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
            bean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    @Override
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
    
    @Scope(scopeName="prototype")
    @Bean
    public SqlMapper sqlHelper() {
    	return  new SqlMapper(sqlSessionFactory.openSession());
    }

}
